'use strict';

angular.module('afasApp')
  .controller('StudentRegistrationCtrl', ['$scope', 'Services', '$state', '$filter', '$stateParams', '_', function ($scope, Services, $state, $filter, $stateParams, _) {

    $scope.sr = [];

    $scope.condition = [];
    $scope.condition[1] = 'Free Repeat';
    $scope.condition[2] = 'Sponsored';
    $scope.condition[3] = 'Other';
  }])
  .controller('StudentRegistrationCreateCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', '$modal', function ($scope, Services, $state, $stateParams, $filter, _, $modal) {

    $scope.courseschedules        = [];
    $scope.studentCourseSchedules = [];
    $scope.coursetypes            = [];
    $scope.terms                  = [];
    $scope.timeclasses            = [];
    $scope.dayclasses             = [];
    $scope.students               = [];
    $scope.termSelected           = false;
    $scope.errors                 = {};

    // INITIALIZE NEW SR OBJECT
    $scope.srNew = {
      'DateTime'       : new Date(),
      'PaymentStatusId': 1,
      'Student'        : {},
      'CourseSchedule'     : {}
    };

    function reFormat() {
      $scope.courseArray = [];
      angular.forEach($scope.timeclasses, function(valueA, keyA){
        $scope.courseArray[valueA.Id] = [];
        angular.forEach($scope.dayclasses, function(valueB, keyB){
          this[valueA.Id][valueB.Id] = {};
          this[valueA.Id][valueB.Id].status = 0;
          this[valueA.Id][valueB.Id].content = [];
        }, this);
      }, $scope.courseArray);

      angular.forEach($scope.courseschedules, function(value, key){
        if (typeof this[value.TimeClass.Id] != 'undefined') {
          this[value.TimeClass.Id][value.DayClass.Id].status = 1;
          var content = value;
          this[value.TimeClass.Id][value.DayClass.Id].content.push(content);
        };
      }, $scope.courseArray);
    }

    // SEARCH STUDENT TO REGISTER
    $scope.searchKey = $stateParams.key;
    // console.log($stateParams);
    $scope.searchText = $scope.searchKey;
    $scope.params = {
      'is_valid': true,
      'keyword': $scope.searchText,
      'include': 'all,latest_placement_test,latest_enrollment'
    };
    $scope.searchStudent = function() {
      $state.go( '^.searchList', {key: $scope.searchText} );
    };

    // GET STUDENT ID
    $scope.srNew.Student.Id = $stateParams.id;

    $scope.pagesize = 200;

    $scope.pagination = {
        current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('students', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.students = results.data;
      });
    }

    if ($stateParams.key) {
      getResultsPage(1);
    };

    // IF STUDENT IS SELECTED
    if ($scope.srNew.Student.Id) {
      $scope.srNew.Student.Id = $scope.srNew.Student.Id;
      $scope.filterTable = {
        'CourseType' : {},
        'Term' : {}
      };

      // LOAD STUDENT
      Services.getItem('students', $scope.srNew.Student.Id, { 'include': 'all,latest_placement_test,latest_enrollment,contacts' })
      .then(function(results){
        $scope.currStudent = results.data;
      });

      // LOAD COURSE TYPES
      Services.getItems('course_types')
      .then(function(results){
        $scope.coursetypes = results.data;
      });

      // LOAD TERMS
      $scope.callTerm = function () {
        var paramCourse = {
          'course_type': $scope.filterTable.CourseType.Id,
          'order_by': 'year',
          'order_type': 'desc',
          'getall': true
        };
        Services.getItems('terms', paramCourse)
        .then(function( results ) {
          $scope.terms = results.data;
        });
      };

      $scope.showTable = function () {
        $scope.termSelected = true;

        var paramDayClasses = {
          'include': 'course_type'
        };

        var paramTimeClasses = {
          'include': 'course_type'
        };

        Services.getItems($scope.DAYCLASS_URL, paramDayClasses)
        .then(function( results ) {
          $scope.dayclasses = results.data;
          $scope.dayclasses = _.filter($scope.dayclasses, function(obj) {
            return obj.CourseType.Id === $scope.filterTable.CourseType.Id;
          });
          $scope.dayclasses = _.sortBy($scope.dayclasses, function(obj){
            return obj.DayRange;
          });


          Services.getItems($scope.TIMECLASS_URL, paramTimeClasses)
          .then(function( results ) {
            $scope.timeclasses = results.data;
            $scope.timeclasses = _.filter($scope.timeclasses, function(obj) {
              return obj.CourseType.Id === $scope.filterTable.CourseType.Id;
            });

            var paramCourse = {
              'term': $scope.filterTable.Term.Id,
              'include': 'all,enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,staffs,terms',
              'getall' : true
            };

            Services.getItems($scope.COURSESCHEDULE_URL, paramCourse)
            .then(function( results ) {
              $scope.courseschedules = results.data;

              angular.forEach($scope.courseschedules, function(value, key){
                value.SequenceForOrder = value.Course.CourseLevel.Sequence;
                value.SuffixForOrder = value.Suffix;
              });

              // var ind = _.filter($scope.courseschedules, function(obj) {
              //   return obj.Course.TeacherType === 1;
              // });
              // var com = _.filter($scope.courseschedules, function(obj) {
              //   return obj.Course.TeacherType === 2;
              // });
              // var nat = _.filter($scope.courseschedules, function(obj) {
              //   return obj.Course.TeacherType === 0;
              // });

              // ind = $filter('orderBy')(ind, ['SequenceForOrder', 'SuffixForOrder']);
              // com = $filter('orderBy')(com, ['SequenceForOrder', 'SuffixForOrder']);
              // nat = $filter('orderBy')(nat, ['SequenceForOrder', 'SuffixForOrder']);

              // $scope.courseschedules = [];
              // angular.forEach(ind, function(value, key){
              //   $scope.courseschedules.push(value);
              // });
              // angular.forEach(com, function(value, key){
              //   $scope.courseschedules.push(value);
              // });
              // angular.forEach(nat, function(value, key){
              //   $scope.courseschedules.push(value);
              // });

              $scope.courseschedules = $filter('orderBy')($scope.courseschedules, ['SequenceForOrder', 'SuffixForOrder']);

              reFormat();
            });
          });
        });

      };

      $scope.resetTable = function () {
        $scope.termSelected = false;
      };

      $scope.addSR = function(path) {
        $scope.errors = {};
        $scope.srNew.CourseCompletionStatus = 0;
        Services.add('enrollments', $scope.srNew)
        .then(function(results){
          $state.go( path );
        }, function(results){
          if (results.status == 400) {
            $scope.errors = results.data;
          }
        });
      };

      $scope.resetStudent = function(){
        $state.go( '^.new', {id: ''} );
      };

      // MODAL CONTROLLER
      var SRModalCtrl = ['$scope', '$rootScope', '$modalInstance', 'Services', 'currStudent', 'course', 'addSR', '$filter', '_', function($scope, $rootScope, $modalInstance, Services, currStudent, course, addSR, $filter, _){

        $scope.currStudent = currStudent;
        $scope.course = {};
        Services.getItem('course_schedules', course, {'include': 'all,course_level,term,day_class,time_class'})
        .then(function(results){
          $scope.course = results.data;
        });

        $scope.cancel = function () {
          $modalInstance.dismiss('cancel');
        };

        $scope.confirm = function (path) {
          addSR(path);
          $modalInstance.dismiss('cancel');
        };
      }];

      $scope.openModal = function () {
        var modalInstance = $modal.open({
          templateUrl: 'srConfirmation.html',
          controller: SRModalCtrl,
          resolve: {
            currStudent: function () {
              return $scope.currStudent;
            },
            course: function () {
              return $scope.srNew.CourseSchedule.Id;
            },
            addSR: function () {
              return $scope.addSR;
            }
          }
        });
        modalInstance.result.then(function (selectedItem) {
          payment.discounts = selectedItem;
        }, function () {
          console.log('Modal dismissed at: ' + new Date());
        });
      };
    }
  }])
  .controller('SRsingleCtrl', ['$scope', 'ServicesLS', '$state', '$stateParams', '$filter', '_', function ($scope, ServicesLS, $state, $stateParams, $filter, _) {

    console.log(_);
    console.log($filter);

    $scope.sr = {};
    $scope.currentID = $stateParams.id;
    $scope.courseTypes = ServicesLS.getItems('courseTypes');
    $scope.students = ServicesLS.getItems('students');
    $scope.sr = ServicesLS.getItem('studentregistration', $stateParams.id);

    // var timeParsed = $scope.sr.Time.split(':');

    $scope.update = function(){

    };
  }]);